import serial
import serial.tools.list_ports


class SerialProcess:
    def __init__(self):
        self.serial_port = None

    def list_serial_port(self):
        ports = serial.tools.list_ports.comports()
        return ports

    def open_serial_port(self, port, baudrate=2000000):
        try:
            self.serial_port = serial.Serial(
                port=port,
                baudrate=baudrate,
                timeout=0.1  # 设置较短的超时时间
            )
            self.serial_port.set_buffer_size(65535, 8192)
            print(f'数据 成功连接串口{port},波特率{baudrate}')

        except KeyboardInterrupt:
            print("Stop")
        except Exception as e:
            print(f"串口错误: {str(e)}")

    def send_command(self, command):
        try:
            self.serial_port.write(bytearray(command))

        except Exception as e:
            print(f"串口错误: {str(e)}")

    def read_data(self, packet_len):
        try:
            packet = self.serial_port.read(packet_len)
            return packet
        except Exception as e:
            print(f"串口错误: {str(e)}")

    def close_serial_port(self):
        if self.serial_port and self.serial_port.is_open:
            self.serial_port.close()
